package com.whitecat.voting.service;

import com.github.pagehelper.PageHelper;
import com.whitecat.voting.dao.CandidateMapper;
import com.whitecat.voting.entity.Candidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CandidateService {

    private final CandidateMapper candidateMapper;

    public CandidateService(CandidateMapper candidateMapper) {
        this.candidateMapper = candidateMapper;
    }

    public Candidate findById(String openId) {
        return candidateMapper.selectByPrimaryKey(openId);
    }

    public List<Candidate> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize, "create_time");
        Candidate condition = new Candidate();
        condition.setAvailable(1);
        return candidateMapper.select(condition);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrModify(Candidate entity) {
        String openId = entity.getOpenId();
        Candidate record = candidateMapper.selectByPrimaryKey(openId);
        int count;
        if (record == null) {
            count = candidateMapper.insertSelective(entity);
        } else {
            count = candidateMapper.updateByPrimaryKeySelective(entity);
        }
        return count > 0;
    }
}
